package com.youbo.ysqd.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 用于模拟HTTP请求中GET/POST方式
 * @author macy
 */
public class HttpUtils {


    public static void post(String urlPath, String Json,String token,Callback callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result=post(urlPath,Json,token);
                if(null!=callback){
                    callback.completed(result);
                }
            }
        }).start();
    }

    //发送JSON字符串 如果成功则返回成功标识。
    public static String post(String urlPath, String Json,String token) {

        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);



            conn.setRequestProperty("Content-Type","application/json");

            if(null!=token){
                conn.setRequestProperty("Cookie","tk="+ token +"; sidebarStatus=0;");
                conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36");
            }else{
                conn.setRequestProperty("User-Agent","56si ji/3.1.10 (iPhone; iOS 14.4.2; Scale/2.00)");
            }

            /**
             *
             */


            // 往服务器里面发送数据
            if (Json != null && !"".equals(Json)) {
                byte[] writebytes = Json.getBytes("UTF-8");
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(writebytes);
                outwritestream.flush();
                outwritestream.close();
            }
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}